<template>
    <div class="page">
        <el-row :gutter="20">
            <el-col :span="24" :xs="24" :sm="24" :lg="24">
                <div class="grid-content bg-purple">
                    <div class="panel">
                        <div class="panel-body">
                            <el-row :gutter="20">
                                <el-col :span="3">
                                    <h5>账号管理</h5>
                                </el-col>
                                <el-col :span="3" :offset="18"><el-button size="medium" type="warning" style="background: rgba(248,154,55,1);" @click="openCreateDialog">新增</el-button></el-col>
                            </el-row>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="24" :xs="24" :sm="24" :lg="24">
                <div class="grid-content bg-purple">
                    <div class="panel">
                        <div class="panel-body">
                            <el-row :gutter="20">
                                <el-col :span="24" :xs="24" :sm="24" :lg="24">
                                    <el-table :data="accountData.data" style="width: 100%" v-loading="listLoading" @row-click="rowClick">
                                        <el-table-column
                                            prop="name"
                                            label="姓名">
                                        </el-table-column>
                                        <el-table-column
                                            prop="role_name"
                                            label="角色">
                                        </el-table-column>
                                        <el-table-column
                                            prop="permission"
                                            label="权限">
                                        </el-table-column>
                                        <el-table-column
                                            prop="created_at"
                                            label="创建时间">
                                        </el-table-column>
                                    </el-table>
                                </el-col>
                            </el-row>
                        </div>
                        <div class="panel-footer text-right">
                            <el-pagination @size-change="sizeChange" @current-change="currentChange"
                                           :current-page="queryParams.page"
                                           :page-sizes="[5, 10, 20, 50]"
                                           :page-size="queryParams.paginate"
                                           layout="total, sizes, prev, pager, next, jumper"
                                           :total="accountData.total">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <el-dialog title="新增" :visible.sync="createDialog" width="30%" :before-close="handleCreateClose">
            <el-form ref="addForm" :rules="createRule" :model="createParams" label-width="80px">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="createParams.name"></el-input>
                </el-form-item>
                <el-form-item label="登录账号" prop="phone">
                    <el-input v-model="createParams.phone" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password">
                    <el-input type="password" v-model="createParams.password"  minlength="6" maxlength="18"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role_name">
                    <el-input v-model="createParams.role_name"></el-input>
                </el-form-item>
                <el-form-item label="权限">
                    <template v-for="(group,key) in allPermissions.data">
                        <el-checkbox :indeterminate="group.isIndeterminate" v-model="group.checkall" @change="handleCheckAllChange(key)">{{group.modular_name}}</el-checkbox>
                        <div style="margin: 15px 0;"></div>
                        <el-checkbox-group v-model="createParams.permission[key].list" @change="handleCheckedPermissionChange(key)">
                            <el-checkbox v-for="permission in group.list" :label="permission.id" :key="permission.id">{{permission.name}}</el-checkbox>
                        </el-checkbox-group>
                    </template>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleCreateClose">取 消</el-button>
                <el-button type="warning" style="background: rgba(248,154,55,1);" @click="createAccount()">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog :visible.sync="editDialog" width="30%" :before-close="handleEditClose">
             <span slot="title" class="dialog-header">
                 <el-row>
                    <el-col :span="8">
                        <p style="font-size: 24px;">{{detailData.name}}</p>
                    </el-col>
                    <el-col :span="16">
                        <el-row v-if="editing">
                            <el-col :span="8" :offset="8" v-if="editBtn"><el-button  size="medium" type="warning" style="background: rgba(248,154,55,1);"  @click="editQuery">保存</el-button></el-col>
                            <el-col :span="8" v-if="editBtn"><el-button  size="medium" type="danger"  @click="delQuery">删除</el-button></el-col>
                        </el-row>
                        <el-row v-else>
                            <el-col :span="8" :offset="8" v-if="editBtn"><el-button  size="medium" type="warning" style="background: rgba(248,154,55,1);"  @click="enableEdit">编辑</el-button></el-col>
                            <el-col :span="8" v-if="editBtn"><el-button  size="medium" type="danger"  @click="delQuery">删除</el-button></el-col>
                        </el-row>
                    </el-col>
                 </el-row>
                 <el-row>
                    <el-tabs v-model="tabName" @tab-click="tabClick">
                        <el-tab-pane label="管理员信息" name="info">
                            <el-form ref="editForm" :rules="editRule" :model="detailData" label-width="120px">
                                <el-form-item label="管理员姓名：" prop="name">
                                    <el-input v-model="detailData.name" :disabled="!editing"></el-input>
                                </el-form-item>
                                <el-form-item label="账号：" prop="phone">
                                    <el-input v-model="detailData.phone" :disabled="!editing" maxlength="11"></el-input>
                                </el-form-item>
                                <el-form-item label="密码：" prop="password">
                                    <el-input v-model="detailData.password" :disabled="!editing"  minlength="6" maxlength="18"></el-input>
                                </el-form-item>
                                <el-form-item label="角色：" prop="role_name">
                                    <el-input v-model="detailData.role_name" :disabled="!editing"></el-input>
                                </el-form-item>
                                <el-form-item label="创建时间：">
                                    <p>{{detailData.created_at}}</p>
                                </el-form-item>
                                <el-form-item label="权限">
                                    <template v-for="(group,key) in edit_allPermissions.data">
                                        <el-checkbox :indeterminate="group.isIndeterminate" :disabled="!editing" v-model="group.checkall" @change="edithandleCheckAllChange(key)">{{group.modular_name}}</el-checkbox>
                                        <div style="margin: 5px 0;"></div>
                                        <el-checkbox-group v-model="detailData.permission[key].list" @change="edithandleCheckedPermissionChange(key)">
                                            <el-checkbox v-for="permission in group.list" :disabled="!editing" :label="permission.id" :key="permission.id">{{permission.name}}</el-checkbox>
                                        </el-checkbox-group>
                                    </template>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="操作日志" name="log">
                            <el-table :data="logData.data" style="width: 100%" >
                                <el-table-column prop="created_at">
                                </el-table-column>
                                <el-table-column >
                                    <template slot-scope="scope">
                                        <el-row>
                                            {{scope.row.name}}{{scope.row.operation}}
                                        </el-row>
                                        <el-row v-if="scope.row.history!=null&&scope.row.actuality!=null">
                                            <p>修改前：<br><span v-for="(item,index) in scope.row.history">{{index}}:{{item}}<br></span></p>
                                            <p>修改后：<br><span v-for="(item,index) in scope.row.actuality">{{index}}:{{item}}<br></span></p>
                                        </el-row>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-pagination @size-change="logSizeChange" @current-change="logCurrentChange"
                                           :current-page="queryLogParams.page"
                                           :page-sizes="[5,10, 20, 50]"
                                           :page-size="queryLogParams.paginate"
                                           layout="total, sizes, prev, pager, next, jumper"
                                           :total="logData.total">
                            </el-pagination>
                        </el-tab-pane>
                    </el-tabs>
                </el-row>
             </span>
        </el-dialog>
    </div>
</template>

<script>
    import api from '../apis'
    import Vue from 'vue';
    import store from '../store'
    export default {
        name: "Account",
        data(){
            // let JSON = global.JSON;
            let checkMobile = (rule, value, callback) =>
            {
                let phone=/^[1][3,4,5,7,8][0-9]{9}$/;
                if (!phone.test(value)) {
                    callback(new Error('请输入正确的手机号'));
                } else {
                    callback();
                }
            };
            return {
                //列表加载动画开关
                listLoading:false,
                //列表请求参数
                queryParams:{
                    page:1,
                    paginate:10,
                },
                //日志请求参数
                queryLogParams:{
                    page:1,
                    paginate:5,
                    type:2,
                    uid:'',
                },
                //列表数据
                accountData:{
                    data:[],
                    total:0,
                },
                //日志数据
                logData:{
                    data:[],
                    total:0,
                },
                //新增对话框开关
                createDialog:false,
                //修改对话框开关
                editDialog:false,
                //是否开启修改
                editing:false,
                //编辑对话框按钮显示隐藏状态
                editBtn:true,
                //默认标签页
                tabName:'info',
                //新增请求参数
                createParams:{
                    phone:'',
                    password:'',
                    role_name:'',
                    name:'',
                    permission:[

                    ],
                },
                //新增对话框全部权限数据
                allPermissions:{
                    data:[

                    ],
                },
                //详情对话框全部权限数据
                edit_allPermissions:{
                    data:[

                    ],
                },
                //创建验证规则
                createRule:{
                    phone: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        {validator: checkMobile, trigger: 'blur'},
                    ],
                    name: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                    ],
                    password:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 18, message: '长度在 6 到 18位之间', trigger: 'blur' }
                    ],
                    role_name:[
                        { required: true, message: '请输入角色', trigger: 'blur' },
                    ],
                },
                //修改验证规则
                editRule:{
                    phone: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        {validator: checkMobile, trigger: 'blur'}
                    ],
                    name: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                    ],
                    role_name:[
                        { required: true, message: '请输入角色', trigger: 'blur' },
                    ],
                },
                //详情数据
                detailData:{
                    phone:'',
                    role_name:'',
                    name:'',
                    password:'',
                    permission:[

                    ],
                },
            }
        },
        methods:{
            /**
             * 请求账号列表
             */
            queryAccount()
            {
                this.listLoading = true;
                api.accountData.fetch(this.queryParams).then(response=>{
                    this.accountData = response.data;
                    this.listLoading = false;
                }).catch(errors=>{
                    this.$message.error('请求失败');
                });
            },
            /**
             * 根据id请求详情
             */
            fetchById(id)
            {
                api.accountData.fetchById(id).then(response=>{
                    this.detailData = response.data.data;
                    this.edit_allPermissions.data = [];
                    let temp_data = response.data.data.allPermission;
                    let hadPermission = JSON.parse(JSON.stringify(this.detailData.permission));
                    this.detailData.permission = JSON.parse(JSON.stringify(temp_data));
                    for(let i in temp_data){
                        temp_data[i].checkall = false;
                        temp_data[i].isIndeterminate = false;
                        this.edit_allPermissions.data.push(JSON.parse(JSON.stringify(temp_data[i])));
                    }
                    for(let i in this.detailData.permission){
                        if(typeof(hadPermission[i])!="undefined"&&hadPermission[i]!=''){
                            this.detailData.permission[i].list = [];
                            for(let j in hadPermission[i].list){
                                this.detailData.permission[i].list.push(hadPermission[i].list[j].id)
                            }
                            if(hadPermission[i].list.length==this.edit_allPermissions.data[i].list.length){
                                this.edit_allPermissions.data[i].checkall = true;
                            }else{
                                this.edit_allPermissions.data[i].isIndeterminate = true;
                            }
                        }else{
                            this.detailData.permission[i].list = [];
                        }
                    }
                }).catch(errors=>{
                    this.$message.error('请求失败，'+response.data.resultCode);
                });
            },
            /**
             * 删除请求
             */
            delQuery(){
                this.$confirm('确认删除用户？', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    api.accountData.destroy(this.detailData.id).then(response=>{
                        this.queryAccount();
                        this.handleEditClose();
                        this.$message.success('删除成功');
                    }).catch(errors=>{
                        // this.$message.error('请求失败');
                        this.$message.error(errors.response.data.resultMessage);
                    });
                }).catch(() => {

                });
            },
            /**
             * 修改请求
             */
            editQuery(){
                api.accountData.update(this.detailData).then(response=>{
                    for (let i in this.accountData.data){
                        if(this.accountData.data[i].id==this.detailData.id){
                            Vue.set(this.accountData.data, i, response.data.data);
                            break;
                        }
                    }
                    this.handleEditClose();
                    this.editing = false;
                    this.$message.success('更新成功');
                }).catch(errors=>{
                    this.$message.error('请求失败');
                });
            },
            /**
             * 修改对话框点击修改按钮
             */
            enableEdit(){
                this.editing = true;
            },
            /**
             * 改变每页数量的时候请求列表
             * @param size
             */
            sizeChange(size)
            {
                this.queryParams.paginate = size;
                this.queryAccount();
            },
            /**
             * 日志列表每页数量的时候
             */
            logSizeChange(size){
                this.queryLogParams.paginate = size;
                this.fetchLogs();
            },
            /**
             * 改变当前页的时候请求列表
             * @param index
             */
            currentChange(index)
            {
                this.queryParams.page = index;
                this.queryAccount();
            },
            /**
             * 日志列表改变当前页的时候请求列表
             */
            logCurrentChange(index){
                this.queryLogParams.page = index;
                this.fetchLogs();
            },
            /**
             * 打开新增对话框
             */
            openCreateDialog()
            {
                this.fetchPermissions();
                this.createDialog = true;
            },
            /**
             * 关闭新增对话框时处理
             */
            handleCreateClose()
            {
                this.$refs['addForm'].resetFields();
                this.createDialog = false;
            },
            /**
             * 关闭详情对话框时处理
             */
            handleEditClose()
            {
                this.edit_allPermissions.data = [];
                this.detailData ={
                    phone:'',
                        role_name:'',
                        name:'',
                        password:'',
                        permission:[

                    ],
                },
                this.editDialog = false;
            },
            /**
             * 列表行选中
             * @param row
             * @param event
             * @param column
             */
            rowClick(row, event, column)
            {
                this.fetchById(row.id,this.fetchByIdParams);
                this.detailData.id = row.id;
                this.editDialog = true;
                this.queryLogParams.uid = row.id;
                this.fetchLogs();
            },
            /**
             * 获取权限列表
             */
            fetchPermissions()
            {
                api.accountData.fetchPermissions().then(response=>{
                    let temp_data = response.data.data;
                    this.createParams.permission = JSON.parse(JSON.stringify(temp_data));
                    this.allPermissions.data = [];
                    for(let i in temp_data){
                        temp_data[i].checkall = false;
                        temp_data[i].isIndeterminate = false;
                        this.allPermissions.data.push(temp_data[i]);
                    }
                    for(let i in this.createParams.permission){
                        this.createParams.permission[i].list = [];
                    }
                }).catch(errors=>{

                });
            },
            /**
             *  权限单选按钮选中
             * @param key
             */
            handleCheckedPermissionChange(key)
            {
                let count = this.createParams.permission[key].list.length;
                this.allPermissions.data[key].checkall = count === this.allPermissions.data[key].list.length;
                this.allPermissions.data[key].isIndeterminate = count>0&&count<this.allPermissions.data[key].list.length;

            },
            /**
             *  修改权限单选按钮选中
             * @param key
             */
            edithandleCheckedPermissionChange(key)
            {
                let count = this.detailData.permission[key].list.length;
                this.edit_allPermissions.data[key].checkall = count === this.edit_allPermissions.data[key].list.length;
                this.edit_allPermissions.data[key].isIndeterminate = count>0&&count<this.edit_allPermissions.data[key].list.length;

            },
            /**
             * 权限分组全选
             * @param key
             */
            handleCheckAllChange(key)
            {
                if(this.allPermissions.data[key].checkall==false){
                    this.createParams.permission[key].list = [];
                }else{
                    this.createParams.permission[key].list = [];//这里必须先清空再添加
                    for(let i in this.allPermissions.data[key].list){
                        this.createParams.permission[key].list.push(this.allPermissions.data[key].list[i].id);
                    }
                }
                this.allPermissions.data[key].isIndeterminate = false;
            },
            /**
             * 修改时权限分组全选
             */
            edithandleCheckAllChange(key)
            {
                if(this.edit_allPermissions.data[key].checkall==false){
                    this.detailData.permission[key].list = [];
                }else{
                    this.detailData.permission[key].list = [];//这里必须先清空再添加
                    for(let i in this.edit_allPermissions.data[key].list){
                        this.detailData.permission[key].list.push(this.edit_allPermissions.data[key].list[i].id);
                    }
                }
                this.edit_allPermissions.data[key].isIndeterminate = false;
            },
            /**
             * 新增账号请求
             */
            createAccount()
            {
                this.$refs['addForm'].validate((valid) =>{
                    if(valid){
                        api.accountData.store(this.createParams).then(response=>{
                            this.$message.success('新增成功');
                            this.handleCreateClose();
                            this.jumpToLastPage();
                        }).catch(errors=>{
                            this.$message.error('请求失败，'+response.data.resultCode);
                        });
                    }else{
                        return false;
                    }
                });
            },
            /**
             * 跳转到最后一页
             */
            jumpToLastPage ()
            {
                let last = Math.ceil(this.accountData.total / this.queryParams.paginate);
                if (this.queryParams.page < last) {
                    this.queryParams.page = last;
                }
                this.queryAccount();
            },
            /**
             * 编辑对话框标签页切换
             */
            tabClick(tab, event)
            {
                if(tab.name=='info'){
                    this.editBtn = true;
                }else{
                    this.editBtn = false;
                }
            },
            /**
             * 操作日志请求
             */
            fetchLogs()
            {
                api.log.fetch(this.queryLogParams).then(response=>{
                    this.logData = response.data;
                    for(let i in this.logData.data){
                        if(this.logData.data[i].actuality!=null){
                            this.logData.data[i].actuality = JSON.parse(this.logData.data[i].actuality);
                        }
                        if(this.logData.data[i].history!=null){
                            this.logData.data[i].history = JSON.parse(this.logData.data[i].history);
                        }
                    }
                }).catch(errors=>{
                    this.$message.error('请求失败，'+response.data.resultCode);
                })
            }
        },
        mounted (){
            this.queryAccount();
        }
    }
</script>

<style lang="scss">

</style>
